<?
/*Version 0.3 2011-04-25*/
AddEventHandler("iblock", "OnAfterIBlockElementUpdate", "DoIBlockAfterSave");
AddEventHandler("iblock", "OnAfterIBlockElementAdd", "DoIBlockAfterSave");
AddEventHandler("catalog", "OnPriceAdd", "DoIBlockAfterSave");
AddEventHandler("catalog", "OnPriceUpdate", "DoIBlockAfterSave");
function DoIBlockAfterSave($arg1, $arg2 = false)
{
	$ELEMENT_ID = false;
	$IBLOCK_ID = false;
	$OFFERS_IBLOCK_ID = false;
	$OFFERS_PROPERTY_ID = false;
	if (CModule::IncludeModule('currency'))
		$strDefaultCurrency = CCurrency::GetBaseCurrency();

	//Check for catalog event
	if(is_array($arg2) && $arg2["PRODUCT_ID"] > 0)
	{
		//Get iblock element
		$rsPriceElement = CIBlockElement::GetList(
			array(),
			array(
				"ID" => $arg2["PRODUCT_ID"],
			),
			false,
			false,
			array("ID", "IBLOCK_ID")
		);
		if($arPriceElement = $rsPriceElement->Fetch())
		{
			$arCatalog = CCatalog::GetByID($arPriceElement["IBLOCK_ID"]);
			if(is_array($arCatalog))
			{
				//Check if it is offers iblock
				if($arCatalog["OFFERS"] == "Y")
				{
					//Find product element
					$rsElement = CIBlockElement::GetProperty(
						$arPriceElement["IBLOCK_ID"],
						$arPriceElement["ID"],
						"sort",
						"asc",
						array("ID" => $arCatalog["SKU_PROPERTY_ID"])
					);
					$arElement = $rsElement->Fetch();
					if($arElement && $arElement["VALUE"] > 0)
					{
						$ELEMENT_ID = $arElement["VALUE"];
						$IBLOCK_ID = $arCatalog["PRODUCT_IBLOCK_ID"];
						$OFFERS_IBLOCK_ID = $arCatalog["IBLOCK_ID"];
						$OFFERS_PROPERTY_ID = $arCatalog["SKU_PROPERTY_ID"];
					}
				}
				//or iblock which has offers
				elseif($arCatalog["OFFERS_IBLOCK_ID"] > 0)
				{
					$ELEMENT_ID = $arPriceElement["ID"];
					$IBLOCK_ID = $arPriceElement["IBLOCK_ID"];
					$OFFERS_IBLOCK_ID = $arCatalog["OFFERS_IBLOCK_ID"];
					$OFFERS_PROPERTY_ID = $arCatalog["OFFERS_PROPERTY_ID"];
				}
				//or it's regular catalog
				else
				{
					$ELEMENT_ID = $arPriceElement["ID"];
					$IBLOCK_ID = $arPriceElement["IBLOCK_ID"];
					$OFFERS_IBLOCK_ID = false;
					$OFFERS_PROPERTY_ID = false;
				}
			}
		}
	}
	//Check for iblock event
	elseif(is_array($arg1) && $arg1["ID"] > 0 && $arg1["IBLOCK_ID"] > 0)
	{
		//Check if iblock has offers
		$arOffers = CIBlockPriceTools::GetOffersIBlock($arg1["IBLOCK_ID"]);
		if(is_array($arOffers))
		{
			$ELEMENT_ID = $arg1["ID"];
			$IBLOCK_ID = $arg1["IBLOCK_ID"];
			$OFFERS_IBLOCK_ID = $arOffers["OFFERS_IBLOCK_ID"];
			$OFFERS_PROPERTY_ID = $arOffers["OFFERS_PROPERTY_ID"];
		}
	}

	if($ELEMENT_ID)
	{
		static $arPropCache = array();
		if(!array_key_exists($IBLOCK_ID, $arPropCache))
		{
			//Check for MINIMAL_PRICE property
			$rsProperty = CIBlockProperty::GetByID("MINIMUM_PRICE", $IBLOCK_ID);
			$arProperty = $rsProperty->Fetch();
			if($arProperty)
				$arPropCache[$IBLOCK_ID] = $arProperty["ID"];
			else
				$arPropCache[$IBLOCK_ID] = false;
		}

		if($arPropCache[$IBLOCK_ID])
		{
			//Compose elements filter
			if($OFFERS_IBLOCK_ID)
			{
				$rsOffers = CIBlockElement::GetList(
					array(),
					array(
						"IBLOCK_ID" => $OFFERS_IBLOCK_ID,
						"PROPERTY_".$OFFERS_PROPERTY_ID => $ELEMENT_ID,
					),
					false,
					false,
					array("ID")
				);
				while($arOffer = $rsOffers->Fetch())
					$arProductID[] = $arOffer["ID"];

				if (!is_array($arProductID))
					$arProductID = array($ELEMENT_ID);
			}
			else
				$arProductID = array($ELEMENT_ID);

			$minPrice = false;
			$maxPrice = false;
			//Get prices
			$rsPrices = CPrice::GetList(
				array(),
				array(
					"PRODUCT_ID" => $arProductID,
				)
			);
			while($arPrice = $rsPrices->Fetch())
			{
				if (CModule::IncludeModule('currency') && $strDefaultCurrency != $arPrice['CURRENCY'])
					$arPrice["PRICE"] = CCurrencyRates::ConvertCurrency($arPrice["PRICE"], $arPrice["CURRENCY"], $strDefaultCurrency);

				$PRICE = $arPrice["PRICE"];

				if($minPrice === false || $minPrice > $PRICE)
					$minPrice = $PRICE;

				if($maxPrice === false || $maxPrice < $PRICE)
					$maxPrice = $PRICE;
			}

			//Save found minimal price into property
			if($minPrice !== false)
			{
				CIBlockElement::SetPropertyValuesEx(
					$ELEMENT_ID,
					$IBLOCK_ID,
					array(
						"MINIMUM_PRICE" => $minPrice,
						"MAXIMUM_PRICE" => $maxPrice,
					)
				);
			}
		}
	}
}

/**
 * Генерация превьюшек для больших изображений
 *
 * @param string $src путь от корня сайта к исходной картинке
 * @param array $params массив параметров phpThumb
 * @return string
 */
function ProcessProductImage($src, $width, $useWatermark = true) {
    $docroot = $_SERVER['DOCUMENT_ROOT'];
    $targetDir = '/upload/generated_thumbs';

    if (is_numeric($src)) if ($src > 0) $src = CFile::GetPath($src);
    if (file_exists($docroot.$src)) {
        $params['w'] = $width;
        if ($useWatermark) {
            $params['fltr'][] = 'wmi|' . $docroot . '/images/watermark.png|C|100';
        }

        $ext = pathinfo($docroot.$src, PATHINFO_EXTENSION);
        $base_name = basename($src, ".".$ext);
        if (!defined("MAKEIMAGE_CODE_GEN_FUNCTION")) define ("MAKEIMAGE_CODE_GEN_FUNCTION", false);
        switch (MAKEIMAGE_CODE_GEN_FUNCTION) { // filesize || md5_file
            case "filesize": $code = md5(serialize($params).filesize($docroot.$src)); break;
            case "md5_file": $code = md5(serialize($params).md5_file($docroot.$src)); break;
            default: $code = md5(serialize($params).$docroot.$src);
        }

        $thumb_file = $targetDir."/".$base_name."_thumb_".$code.".".$ext;

        if (file_exists($docroot.$thumb_file)) {
            return $thumb_file;
        } else {
            require_once($docroot."/bitrix/php_interface/include/phpThumb/phpthumb.class.php"); // Подключаем и иннициализируем phpThumb
            $phpThumb = new phpThumb();
            $phpThumb->src = $src;
            switch ($ext) {
                case "jpg": $phpThumb->f = "jpeg"; break;
                case "gif": $phpThumb->f = "gif"; break;
                case "png": $phpThumb->f = "png"; break;
                default: $phpThumb->f = "jpeg"; break;
            }
            $phpThumb->q = 60;
            $phpThumb->bg = "ffffff";
            $phpThumb->far = "C";
            $phpThumb->aoe = 0;
            if (is_array($params)) {
                foreach ($params as $param=>$value) {
                    $phpThumb->$param = $value;
                }
            }
            $phpThumb->GenerateThumbnail();
            $success = $phpThumb->RenderToFile($docroot.$thumb_file);
            if ($success) return $thumb_file;
            else return false;
        }
    } else {
        return false;
    }
}

function determineCurrentProductVariables()
{
    global $APPLICATION;

    $arParams = array(
	"IBLOCK_TYPE" => "catalog",
	"IBLOCK_ID" => "3",
	"ACTION_VARIABLE" => "action",
	"PRODUCT_ID_VARIABLE" => "id",
	"SECTION_ID_VARIABLE" => "SECTION_ID",
	"SEF_MODE" => "Y",
	"SEF_FOLDER" => "/catalog/",
	"AJAX_MODE" => "N",
	"AJAX_OPTION_SHADOW" => "Y",
	"AJAX_OPTION_JUMP" => "N",
	"AJAX_OPTION_STYLE" => "Y",
	"AJAX_OPTION_HISTORY" => "N",
	"CACHE_TYPE" => "A",
	"CACHE_TIME" => "36000000",
	"CACHE_FILTER" => "N",
	"CACHE_GROUPS" => "Y",
	"DISPLAY_PANEL" => "N",
	"SET_TITLE" => "N",
	"SET_STATUS_404" => "Y",
	"USE_FILTER" => "Y",
	"FILTER_NAME" => "",
	"FILTER_FIELD_CODE" => array(
		0 => "NAME",
		1 => "",
	),
	"DETAIL_PROPERTY_CODE" => array(
		0 => "MANUFACTURER",
		1 => "MATERIAL",
		2 => "COLOR",
		3 => "SPECIALOFFER",
		4 => "NEWPRODUCT",
		5 => "SALELEADER",
		6 => "WIDTH",
		7 => "LENGHT",
		8 => "SIZE",
		9 => "STORAGE_COMPARTMENT",
		10 => "HEIGHT",
		11 => "DEPTH",
		12 => "LIGHTS",
		13 => "SHELVES",
		14 => "RECOMMEND",
		15 => "CORNER",
		16 => "SEATS",
		17 => "MORE_PHOTO",
		18 => "",
	),
	"FILTER_PRICE_CODE" => array(
		0 => "BASE",
	),
	"USE_REVIEW" => "Y",
	"FORUM_ID" => "1",
	"USE_COMPARE" => COption::GetOptionString("eshop", "catalogCompare", "Y", SITE_ID) == "Y" ? "Y" : "N",
	"COMPARE_NAME" => "CATALOG_COMPARE_LIST",
	"COMPARE_FIELD_CODE" => array(
		0 => "PREVIEW_TEXT",
		1 => "DETAIL_PICTURE",
		2 => "",
	),
	"COMPARE_PROPERTY_CODE" => array(
		0 => "NEWPRODUCT",
		1 => "SIZE",
		2 => "ARTNUMBER",
		3 => "MATERIAL",
		4 => "MANUFACTURER",
		5 => "",
	),
	"DISPLAY_ELEMENT_SELECT_BOX" => "N",
	"ELEMENT_SORT_FIELD_BOX" => "name",
	"ELEMENT_SORT_ORDER_BOX" => "asc",
	"COMPARE_ELEMENT_SORT_FIELD" => "sort",
	"COMPARE_ELEMENT_SORT_ORDER" => "asc",
	"PRICE_CODE" => array(
		0 => "BASE",
	),
	"USE_PRICE_COUNT" => "N",
	"SHOW_PRICE_COUNT" => "1",
	"PRICE_VAT_INCLUDE" => "Y",
	"PRICE_VAT_SHOW_VALUE" => "N",
	"SHOW_TOP_ELEMENTS" => "N",
	"PAGE_ELEMENT_COUNT" => COption::GetOptionInt("eshop", "catalogElementCount", "25", SITE_ID),
	"LINE_ELEMENT_COUNT" => "1",
	"ELEMENT_SORT_FIELD" => "sort",
	"ELEMENT_SORT_ORDER" => "asc",
	"LIST_PROPERTY_CODE" => array(
		0 => "NEWPRODUCT",
		1 => "SPECIALOFFER",
		2 => "SALELEADER",
	),
	"LIST_OFFERS_FIELD_CODE" => array(
		0 => "NAME",
		1 => "",
	),
	"LIST_OFFERS_PROPERTY_CODE" => array(
		0 => "COLOR",
		1 => "WIDTH",
		2 => "",
	),
	"INCLUDE_SUBSECTIONS" => "Y",
	"LIST_META_KEYWORDS" => "-",
	"LIST_META_DESCRIPTION" => "-",
	"LIST_BROWSER_TITLE" => "-",
	"SECTION_COUNT_ELEMENTS" => "N",
	"SECTION_TOP_DEPTH" => "1",
	"DETAIL_META_KEYWORDS" => "-",
	"DETAIL_META_DESCRIPTION" => "-",
	"DETAIL_BROWSER_TITLE" => "-",
	"DETAIL_OFFERS_FIELD_CODE" => array(
		0 => "NAME",
		1 => "",
	),
	"DETAIL_OFFERS_PROPERTY_CODE" => array(
		0 => "COLOR",
		1 => "WIDTH",
		2 => "",
	),
	"LINK_IBLOCK_TYPE" => "",
	"LINK_IBLOCK_ID" => "",
	"LINK_PROPERTY_SID" => "",
	"LINK_ELEMENTS_URL" => "link.php?PARENT_ELEMENT_ID=#ELEMENT_ID#",
	"USE_STORE" => "Y",
	"MAIN_TITLE" => "Наличие на складах",
	"STORE_PATH" => "/store/#store_id#",
	"USE_ALSO_BUY" => "Y",
	"ALSO_BUY_ELEMENT_COUNT" => "3",
	"ALSO_BUY_MIN_BUYES" => "2",
	"DISPLAY_TOP_PAGER" => "N",
	"DISPLAY_BOTTOM_PAGER" => "Y",
	"PAGER_TITLE" => "Товары",
	"PAGER_SHOW_ALWAYS" => "N",
	"PAGER_TEMPLATE" => "arrows",
	"PAGER_DESC_NUMBERING" => "N",
	"PAGER_DESC_NUMBERING_CACHE_TIME" => "36000000",
	"PAGER_SHOW_ALL" => "N",
	"AJAX_OPTION_ADDITIONAL" => "",
	"DISPLAY_IMG_WIDTH" => "180",
	"DISPLAY_IMG_HEIGHT" => "225",
	"DISPLAY_DETAIL_IMG_WIDTH" => "280",
	"DISPLAY_DETAIL_IMG_HEIGHT" => "280",
	"DISPLAY_MORE_PHOTO_WIDTH" => "280",
	"DISPLAY_MORE_PHOTO_HEIGHT" => "280",
	"SHARPEN" => "30",
	"SEF_URL_TEMPLATES" => array(
		"sections" => "",
		"section" => "#SECTION_CODE#/",
		"element" => "#SECTION_CODE#/#ELEMENT_CODE#/",
		"compare" => "compare/",
	)
);

$arDefaultUrlTemplates404 = array(
	"sections" => "",
	"section" => "#SECTION_ID#/",
	"element" => "#SECTION_ID#/#ELEMENT_ID#/",
	"compare" => "compare.php?action=COMPARE",
);

$arDefaultVariableAliases404 = array();

$arDefaultVariableAliases = array();

$arComponentVariables = array(
	"SECTION_ID",
	"SECTION_CODE",
	"ELEMENT_ID",
	"ELEMENT_CODE",
	"action",
);

$arParams["VARIABLE_ALIASES"] = Array(
    "SECTION_CODE" => Array("NAME" => 'SECTION_CODE'),
    "ELEMENT_CODE" => Array("NAME" => 'ELEMENT_CODE'),
    "SECTION_ID" => Array("NAME" => 'SECTION_ID'),
    "ELEMENT_ID" => Array("NAME" => 'ELEMENT_ID'),
);
$arParams["SEF_URL_TEMPLATES"] = array(
    "sections" => "",
    "section" => "#SECTION_CODE#/",
    "element" => "#SECTION_CODE#/#ELEMENT_CODE#/",
    "compare" => "compare/",
);

$arVariables = array();

$engine = new CComponentEngine($this);
$engine->addGreedyPart("#SECTION_CODE_PATH#");
$engine->setResolveCallback(array("CIBlockFindTools", "resolveComponentEngine"));

$arUrlTemplates = CComponentEngine::MakeComponentUrlTemplates($arDefaultUrlTemplates404, $arParams["SEF_URL_TEMPLATES"]);
$arVariableAliases = CComponentEngine::MakeComponentVariableAliases($arDefaultVariableAliases404, $arParams["VARIABLE_ALIASES"]);

$componentPage = $engine->guessComponentPath(
    $arParams["SEF_FOLDER"],
    $arUrlTemplates,
    $arVariables
);

if(!$componentPage && isset($_REQUEST["q"]))
    $componentPage = "search";

$b404 = false;
if(!$componentPage)
{
    $componentPage = "sections";
    $b404 = true;
}

if(
    $componentPage == "section"
    && isset($arVariables["SECTION_ID"])
    && intval($arVariables["SECTION_ID"])."" !== $arVariables["SECTION_ID"]
)
    $b404 = true;

if($b404 && $arParams["SET_STATUS_404"]==="Y")
{
    $folder404 = str_replace("\\", "/", $arParams["SEF_FOLDER"]);
    if ($folder404 != "/")
        $folder404 = "/".trim($folder404, "/ \t\n\r\0\x0B")."/";
    if (substr($folder404, -1) == "/")
        $folder404 .= "index.php";

        if($folder404 != $APPLICATION->GetCurPage(true))
        CHTTP::SetStatus("404 Not Found");
}

CComponentEngine::InitComponentVariables($componentPage, $arComponentVariables, $arVariableAliases, $arVariables);
$arResult = array(
    "FOLDER" => $arParams["SEF_FOLDER"],
    "URL_TEMPLATES" => $arUrlTemplates,
    "VARIABLES" => $arVariables,
    "ALIASES" => $arVariableAliases
);

$arVariables["ELEMENT_ID"] = CIBlockFindTools::GetElementID(
    $arVariables["ELEMENT_ID"],
    $arVariables["ELEMENT_CODE"],
    false,
    false,
    array(
        "IBLOCK_ID" => '',
        "IBLOCK_LID" => SITE_ID,
        "IBLOCK_ACTIVE" => "Y",
        "ACTIVE_DATE" => "Y",
        "ACTIVE" => "Y",
        "CHECK_PERMISSIONS" => "Y",
    )
);
    return $arVariables;
}

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/ss_constructor/admin/SolutionEditPageHandler.php");
